package config

import (
	"gorm.io/gorm"
	"obsidian-plugin-server/models"
	"os"
	"strconv"
)

type Config struct {
	App      AppConfig
	Database DatabaseConfig
	JWT      JWTConfig
}

type AppConfig struct {
	Port  string
	Debug bool
}

type DatabaseConfig struct {
	Path string
}

type JWTConfig struct {
	Secret string
}

func Load() *Config {
	return &Config{
		App: AppConfig{
			Port:  getEnv("APP_PORT", ":8111"),
			Debug: getEnvBool("APP_DEBUG", true),
		},
		Database: DatabaseConfig{
			Path: getEnv("DB_PATH", "data.db"),
		},
		JWT: JWTConfig{
			Secret: getEnv("JWT_SECRET", "your-secret-key"),
		},
	}
}

// LoadWithDB 从数据库加载配置
func LoadWithDB(db *gorm.DB) (*Config, error) {
	// 获取或创建 JWT Secret
	jwtSecret, err := models.GetOrCreateJWTSecret(db)
	if err != nil {
		return nil, err
	}

	return &Config{
		App: AppConfig{
			Port:  getEnv("APP_PORT", ":8111"),
			Debug: getEnvBool("APP_DEBUG", true),
		},
		Database: DatabaseConfig{
			Path: getEnv("DB_PATH", "data.db"),
		},
		JWT: JWTConfig{
			Secret: jwtSecret,
		},
	}, nil
}

func getEnv(key, defaultValue string) string {
	if value := os.Getenv(key); value != "" {
		return value
	}
	return defaultValue
}

func getEnvBool(key string, defaultValue bool) bool {
	if value := os.Getenv(key); value != "" {
		if boolValue, err := strconv.ParseBool(value); err == nil {
			return boolValue
		}
	}
	return defaultValue
}
